package 多线程;

/**
 * @description: 栈
 * @author: rock
 * @create:
 **/
public class Stack {
    private Goods goods;
    private Goods[] goodStack;
    private int count;
    private int index;


    public Stack(int count) {
        this.count = count;
        if(this.count<=0){
            this.count = 10;
        }
        goodStack = new Goods[this.count];
        index  = 0;


    }

    public synchronized void push(Goods goods){
        if(index>=count){
            try {
                this.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (index<count){
            goodStack[index] = goods;
            index++;
        }
        System.out.println("生产了"+goods.getGoodsName());
        this.notifyAll();
    }
    public synchronized Goods pop(){
        goods = null;
        if (index>=count){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else if (index>0){
            index--;
            goods = goodStack[index];
            goodStack[index] = null;
            System.out.println("消费了"+goods.getGoodsPrise());
        }
        this.notifyAll();

        return goods;
    }
    //    private Goods[] goodsStack;
//    private int index;
//    private int stackCount;
//
//    public Stack(int stackCount){
//        this.stackCount = stackCount;
//        if (stackCount<=0){
//            stackCount = 10;
//        }
//        goodsStack = new Goods[stackCount];
//        //设置栈项指针初始位置
//        index = 0;
//
//    }
//    //入栈
//    public void push(Goods goods) {
//        if (index>=stackCount){
//            try {
//                this.wait();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
//        //存入当前栈位置
//        if (index<stackCount){
//            goodsStack[index] = goods;
//            //存入之后，栈顶位置++
//            index++;
//        }
//        System.out.println("生产了"+goods.getGoodsName());
//
//    }
//    public Goods pop(){
//        Goods goods = null;
//        if (index>0){
//            index--;
//            goods = goodsStack[index];
//            goodsStack[index] = null;
//            System.out.println("消费了"+goods.getGoodsPrise());
//        }
//
//        return goods;
//    }
}
